<template>
  <view class="content">
		<tnNotify ref="notifyRef" />
		<!-- 安全密钥 -->
		<view class="pwd-key">
			<view><TnIcon name="safe-fill" :type="bookConfig.hasKey?'success':'danger'"></TnIcon></view>
			<view class="tn-purple_text">安全密钥：</view>
			<view v-if="bookConfig.hasKey" class="show-key tn-text-bold tn-orangered_text">
				<view>{{ bookConfig.privateKey }}</view>
				<view style="margin-left: auto;" @click="changeTogglePlainKey"><TnIcon :name="bookConfig.plainKey ? 'eye' : 'eye-hide'"></TnIcon></view>
			</view>
			<view v-else class="show-key tn-gray_text">您还没设置安全密钥！</view>
			<view class="set-icon" @click="setPrivateKey"><TnIcon name="set" size="34rpx"></TnIcon></view>
		</view>
    <view v-if="bookConfig.hasBook" class="blocks">
      <view class="block-box" v-for="block in blocks" :key="block.id">
        <view class="block-name">{{ block.name }}</view>
        <view class="block-items">
          <view class="item" v-for="item in block.funcs" :key="item._id"
						:class="item._id == bookConfig.currentBookId ? 'active': ''"
						@click="showAccountList(item)"
						@longpress="toManageBook(item)"
					>
            <view class="icon">
              <image :src="item.icon" mode="aspectFit" />
            </view>
            <view class="name">{{ item.name }}</view>
          </view>
					<view class="item" @click="showPopupAction = true">
					  <view class="icon">
					    <image src="/static/icons/editor.png" mode="aspectFit" />
					  </view>
					  <view class="name">新建</view>
					</view>
        </view>
      </view>
    </view>
		<view class="blank-content" v-else>
			<view>
				<view>
					<TnEmpty mode="list" color="tn-gray">
						<template #tips>您还没有密码本，赶紧建个试试吧</template>
					</TnEmpty>
				</view>
				<view class="create-btn">
					<TnButton :text="true" @click="showPopupAction = true">新建密码本</TnButton>
				</view>
			</view>
		</view>
		<!-- 本子内各账户 -->
		<view v-if="bookConfig.hasBook" class="book-list">
			<view class="list-op">
				<view>
					<view>【{{ bookConfig.currentBookName }}】</view>
				</view>
				<view @click="createNewAccount">
					<text class="tn-type-primary_text">新建+</text>
				</view>
				<view @click="toggleHideAll">
					<TnIcon :name="bookData.explainAll ? 'eye':'eye-hide'"></TnIcon>
				</view>
			</view>
			<view v-if="bookData.hasAccount" class="list-content">
				<view v-for="(item, index) in bookData.accounts">
					<view class="name">
						<view class="nindex"> {{ index + 1 }}、</view>
						<view class="ntext">
							<view style="word-wrap: break-word;">{{ item.username }}</view>
							<view style="margin-left:15rpx;" @click="toggleItemExplain(index, item)">
								<TnIcon :name="item.explain ? 'eye':'eye-hide'"></TnIcon>
							</view>
						</view>
						<view @click="editAccount(item)"><TnIcon name="edit"></TnIcon></view>
					</view>
					<view class="secret">
						<text v-if="item.explain">{{ item.userkey }}</text>
						<text v-else>{{ item.keyHide }}</text>
					</view>
					<view class="tn-grey_text tn-text-xs note">
						{{ item.note }}
					</view>
				</view>
			</view>
			<view v-else class="tn-mt-xl">
				<TnEmpty mode="list" color="tn-gray">
					<template #tips>密码本内还没有记录，赶紧新建个试试吧</template>
				</TnEmpty>
			</view>
		</view>
	
		<!-- 新建本弹窗 -->
		<TnPopup v-model="showPopupAction" close-btn width="90%">
		  <view class="popup-box tn-p-xs">
		    <TnTitle title="新建密码本" mode="vLine"></TnTitle>
		    <view class="form">
		      <view class="form-row">
		        <view class="label">
		          名称
		        </view>
		        <view class="value">
		          <input type="text" v-model.trim="categoryData.group_name" placeholder="请输入密码本名称" />
		        </view>
		      </view>
		      <view class="tn-flex-end-end tn-mt">
		        <!-- <TnButton click-modifiers="stop" type="danger" @click="toDeleteCategory">删除</TnButton> -->
		        <view class="tn-mr"></view>
		        <TnButton click-modifiers="stop" type="primary" @click="toSaveCategory">确定</TnButton>
		      </view>
		    </view>
		  </view>
		</TnPopup>
		<!-- 管理本子弹窗 -->
		<TnPopup v-model="manageBook.showAction" open-direction="bottom" close-btn height="300">
			<view class="manage-book">
				<view class="title">管理密码本</view>
				<view class="form-row">
				  <view class="label">
				    名称：
				  </view>
				  <view class="value">
				    <input type="text" v-model.trim="manageBook.bookName" placeholder="请输入要修改的名称" />
				  </view>
				</view>
				<view class="actions">
					<view class="tn-m-sm">
						<TnButton type="danger" plain @click="toDeleteBook">
							<text class="tn-red_text">删除</text>
						</TnButton>
					</view>
					<view class="tn-m-sm">
						<TnButton plain @click="toEditBook">
							<text class="tn-type-primary_text">确定保存</text>
						</TnButton>
					</view>
				</view>
			</view>
		</TnPopup>
		<!-- 密钥模态框 -->
		<TnModal ref="keyModalRef">
			<view class="private-key">
				<view class="key-form">
					<view class="form">
						<view class="form-row">
							<view class="label">密钥</view>
						  <view class="value">
						    <input type="text" v-model.trim="keyModalConfig.privateKey" placeholder="请在此设置您的密钥" />
						  </view>
						</view>
					</view>
				</view>
				<view class="tn-red_text">重要提示：</view>
				<view class="tn-text-sm">
					为了您的数据安全，安全密钥为是<text class="tn-red_text">唯一凭证</text>且保存在您<text class="tn-red_text">本地设备</text>，请<text class="tn-red_text">务必牢记</text>！忘记安全密钥将无法查看正确数据，也<text class="tn-red_text">无法恢复</text>！
				</view>
			</view>
		</TnModal>
		<!-- 新建条目模态框 -->
		<TnModal ref="newAccountRef">
			<view class="private-key">
				<view class="key-form">
					<view class="form">
						<view class="form-row">
							<view class="label">用户名</view>
						  <view class="value">
						    <input type="text" v-model.trim="accountConfig.account" placeholder="请填写登录的用户名" />
						  </view>
						</view>
						<view class="form-row">
							<view class="label">密&nbsp;&nbsp;&nbsp;&nbsp;码</view>
						  <view class="value">
								<input type="text" v-model.trim="accountConfig.passkey" placeholder="请填写登录的密码" />
						  </view>
						</view>
						<view class="form-row">
							<view class="label">备&nbsp;&nbsp;&nbsp;&nbsp;注</view>
						  <view class="value">
								<input type="text" v-model.trim="accountConfig.note" placeholder="请填写备注信息" />
						  </view>
						</view>
					</view>
				</view>
				<view class="tn-flex-end-end" @click="showSaveAccountInfo">
					<view class="tn-red_text tn-text-sm">查看示例</view>
				</view>
			</view>
		</TnModal>
		
		<TnModal ref="infoRef">
			<view class="acc-info">
				<view>
					<view class="title">用户名：</view>
					<view class="info">{{ accountConfig.secret_account }}</view>
				</view>
				<view>
					<view class="title">密&nbsp;&nbsp;&nbsp;&nbsp;码：</view>
					<view class="info">{{ accountConfig.secret_passkey }}</view>
				</view>
				<view>
					<view class="title">备&nbsp;&nbsp;&nbsp;&nbsp;注：</view>
					<view class="info">{{ accountConfig.note }}</view>
				</view>
			</view>
		</TnModal>
  </view>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { TOKEN_KEY } from '@/configs'
  import { getStorageSync, setStorageSync } from '@/utils/store';
  import { callCloudFunction } from '@/utils/cloudfunc';
  import { aesEncrypt, aesDecrypt, rsaEncrypt, rsaDecrypt } from '@/utils/encrypt.js'
	import TnEmpty from '@/uni_modules/tuniaoui-vue3/components/empty/src/empty.vue'
	import TnButton from '@/uni_modules/tuniaoui-vue3/components/button/src/button.vue'
	import TnTitle from '@/uni_modules/tuniaoui-vue3/components/title/src/title.vue'
	import TnPopup from '@/uni_modules/tuniaoui-vue3/components/popup/src/popup.vue'
	import tnNotify from '@/uni_modules/tuniaoui-vue3/components/notify/src/notify.vue'
	import TnCollapse from '@/uni_modules/tuniaoui-vue3/components/collapse/src/collapse.vue'
	import TnCollapseItem from '@/uni_modules/tuniaoui-vue3/components/collapse/src/collapse-item.vue'
	import TnIcon from '@/uni_modules/tuniaoui-vue3/components/icon/src/icon.vue'
	import TnModal from '@/uni_modules/tuniaoui-vue3/components/modal/src/modal.vue'
	
	const PWD_PRIVATE_KEY = 'PWD_PRIVATE_KEY'
	const manageBook = reactive({
		bookId: null,
		showAction: false,
		bookName: '',
	})
	const bookConfig = reactive({
		hasBook: false,
		hasKey: false,
		privateKey: '',
		keyText: '',
		plainKey: false,
		currentBookId: null,
		currentBookName: '',
	});
	const showPopupAction = ref(false)
	const keyModalRef = ref()
	const keyModalConfig = reactive({
		privateKey: ''
	})
	
	const newAccountRef = ref()
	const accountConfig = reactive({
		_id: null,
		group_id: '',
		account: '',
		passkey: '',
		note: '',
		secret_account: '',
		secret_passkey: '',
	})
	
	const infoRef = ref()
	
	// 通知
	const notifyRef = ref(null)
  const blocks = ref([
    {
      id: 1,
      name: '密码本',
      funcs: [
        { id: '1-1', name: '生活账本', icon: '/static/icons/account.png', page: '/pages/account/index'},
      ],
    },
  ])
	
	const bookData = reactive({
		explainAll: false,
		hasAccount: true,
		accounts: [
			{
				_id: 0,
				username: '',
				userkey: '',
				note: '',
				explain: false,
				keyHide: '',
			}
		]
	})
	
	const categoryData = reactive({
	  _id: '',
	  parent_id: '',
	  group_name: '',
	  child_name: '',
	  parent_name: '',
	})
	
	const setCurrentPrivateKey = () => {
		const pkey = getStorageSync(PWD_PRIVATE_KEY)
		if (pkey && pkey.length > 0) {
			bookConfig.keyText = pkey;
			bookConfig.hasKey = true
			keyModalConfig.privateKey = pkey;
			togglePlainKey()
		} else {
			bookConfig.keyText = '';
			bookConfig.hasKey = false
			keyModalConfig.privateKey = '';
		}
	}
	
	const togglePlainKey = () => {
		if (bookConfig.hasKey) {
			if (bookConfig.plainKey) {
				bookConfig.privateKey = bookConfig.keyText
			} else {
				bookConfig.privateKey = '*'.repeat(bookConfig.keyText.length)
			}
		}
	}
	const changeTogglePlainKey = () => {
		bookConfig.plainKey = !bookConfig.plainKey
		togglePlainKey();
	}
	const toggleHideAll = () => {
		const isExplain = !bookData.explainAll
		bookData.explainAll = isExplain;
		bookData.accounts = bookData.accounts.map(item => {
			item.explain = isExplain
			return item
		})
	}
	
	const toggleItemExplain = (i, item) => {
		item.explain = !item.explain
	}

	const setPrivateKey = () => {
		console.log('密钥');
		keyModalRef.value?.showModal({
			title: '密钥设置',
			content: 'Modal内容',
			showCancel: true,
			confirm: () => {
				// console.log(keyModalConfig.privateKey)
				setStorageSync(PWD_PRIVATE_KEY, keyModalConfig.privateKey)
				setCurrentPrivateKey();
			}
		})
	}
	// 管理本子
	const toManageBook = (book) => {
		console.log(book)
		manageBook.bookId = book._id
		manageBook.bookName = book.name
		manageBook.showAction = true
	}
	// 删除本子
	const deleteBook = () => {
		callCloudFunction({
			name: 'ume-group',
			data: { action: 'userDelete', _id: manageBook.bookId, params: {block: 'PWD'}}
		}).then(res => {
			notifyRef.value?.show({
				msg: res.message,
				type: res._id ? 'success' : 'error'
			})
			manageBook.showAction = false
			listBooks();
		})
	}
	const toDeleteBook = () => {
		console.log('删除');
		uni.showModal({
			title: '警告',
			content: '确定删除该密码本吗?，操作不可恢复!',
			success: (res) => {
				if (res.confirm) {
		      deleteBook()
				} else if (res.cancel) {
				}
			}
		});
	}
	
	// 修改本子
	const toEditBook = () => {
		if (!manageBook.bookName) {
			notifyRef.value?.show({
				msg: '请输入要修改的名称!',
				type: 'error'
			})
			return
		}
		callCloudFunction({
			name: 'ume-group',
			data: {action: 'userUpdate', _id: manageBook.bookId, group_name: manageBook.bookName, params: {block: 'PWD'} }
		}).then(res => {
			notifyRef.value?.show({
				msg: res.message,
				type: 'success'
			})
			manageBook.showAction = false
			listBooks();
		})
	}
	
	// 创建记录
	const toCreateNewNote = () => {
		const createData = {
			group_id: bookConfig.currentBookId,
			account: accountConfig.secret_account,
			passkey: accountConfig.secret_passkey,
			note: accountConfig.note
		}
		callCloudFunction({
			name: 'ume-notebook',
			data: {action: 'userCreate', create_data: createData }
		}).then(res => {
			// console.log(res);
			// 重新加载当前本子账户
			listBookAccounts();
		})
	}
	// 保存修改记录
	const toSaveNote = () => {
		const saveData = {
			_id: accountConfig._id,
			group_id: bookConfig.currentBookId,
			account: accountConfig.secret_account,
			passkey: accountConfig.secret_passkey,
			note: accountConfig.note
		}
		callCloudFunction({
			name: 'ume-notebook',
			data: { action: 'userUpdate', save_data: saveData}
		}).then(res => {
			listBookAccounts();
		})
	}
	// 删除记录
	const toDeleteNote = () => {
		console.log(accountConfig._id)
		callCloudFunction({
			name: 'ume-notebook',
			data: { action: 'userDel', _id: accountConfig._id}
		}).then(res => {
			notifyRef.value?.show({
			  msg: res.message,
			  type: 'success'
			})
			// 刷新
			listBookAccounts();
		})
	}
	
	const toDeleteCategory = () => {

	}
	
	const toSaveCategory = () => {
		const groupData = {
			group_name: categoryData.group_name,
		}
		// console.log(groupData);
		callCloudFunction({
			name: 'ume-group',
			data: { action: 'userCreate', params: {block: 'PWD'}, group_data: groupData}
		}).then(res => {
			showPopupAction.value = false
			// console.log('res:', res);
			notifyRef.value?.show({
			  msg: res.message,
			  type: 'success'
			})
			// 刷新
			listBooks();
		})
	}
	
	// 加密函数
	const encryptString = (text) => {
		const secret = bookConfig.privateKey
		const aesText = aesEncrypt(text, secret)
		return rsaEncrypt(aesText)
	}
	// 解密函数
	const decryptString = (text) => {
		const aesSecret = rsaDecrypt(text);
		const decryptStr = aesDecrypt(aesSecret, bookConfig.privateKey)
		return decryptStr ? decryptStr : '密钥可能有误!'
	}
	
	// 修改编辑删除账户
	const editAccount = (item) => {
		if (!bookConfig.hasKey) {
			notifyRef.value.show({
			  msg: '您还未设置密钥！',
			  type: 'error'
			})
			return;
		}
		// console.log(item)
		// 设置数据
		accountConfig._id = item._id
		accountConfig.group_id = bookConfig.currentBookId
		accountConfig.account = item.username
		accountConfig.passkey = item.userkey
		accountConfig.note = item.note
		newAccountRef.value.showModal({
			title: '编辑密码账户',
			content: '',
			maskClosable: true,
			showCancel: true,
			cancelText: '删除',
			cancelStyle: {
				bgColor: '#e6e6e6',
				color: 'tn-red',
			},
			confirmText: '保存',
			confirmStyle: {
				bgColor: 'tn-blue',
				color: '#f8f8f8',
			},
			confirm: () => {
				encryptAccount();
				console.log(accountConfig);
				toSaveNote(); // 保存
			},
			cancel: () => {
				uni.showModal({
					title: '警告',
					content: '确定删除该记录吗，操作不可恢复!',
					success: (res) => {
						if (res.confirm) {
				      toDeleteNote()
						} else if (res.cancel) {
						}
					}
				});
			}
		})
	}
	
	// 新建账户
	const createNewAccount = () => {
		if (!bookConfig.hasKey) {
			notifyRef.value.show({
			  msg: '您还未设置密钥！',
			  type: 'error'
			})
			return;
		}
		// 清空设置数据
		accountConfig._id = null
		accountConfig.group_id = bookConfig.currentBookId
		accountConfig.account = ''
		accountConfig.passkey = ''
		accountConfig.note = ''
		accountConfig.secret_account = ''
		accountConfig.secret_passkey = ''
		newAccountRef.value.showModal({
			title: '新建密码账户',
			content: '',
			showCancel: true,
			cancelStyle: {
				bgColor: '#e6e6e6',
				color: '#f8f8f8',
			},
			confirmStyle: {
				bgColor: 'tn-green',
				color: '#f8f8f8',
			},
			confirm: () => {
				encryptAccount();
				console.log(accountConfig);
				toCreateNewNote(); // 保存
			}
		})
	}
	
	const encryptAccount = () => {
		accountConfig.secret_account = encryptString(accountConfig.account)
		accountConfig.secret_passkey = encryptString(accountConfig.passkey)
	}
	
	const showSaveAccountInfo = () => {
		encryptAccount()
		infoRef.value.showModal({
			title: '保存信息如下',
			content: '',
		})
	}
	
	// 获取当前密码本的账户
	const showAccountList = (item) => {
		bookConfig.currentBookId = item._id
		bookConfig.currentBookName = item.name
		listBookAccounts();
	}
	
	const listBooks = () => {
		callCloudFunction({
			name: 'ume-group',
			data: {action: 'userRetrieve', params: {
				block: 'PWD'
			}}
		}).then(res => {
			// console.log('listBooks:', res);
			blocks.value[0].funcs = res.groups.map(item => {
				return {
					_id: item._id,
					name: item.group_name,
					icon: '/static/icons/psd_book.png',
					page: ''
				}
			})
			bookConfig.hasBook = res.groups.length > 0
			if (bookConfig.hasBook) {
				bookConfig.currentBookId = res.groups[0]._id
				bookConfig.currentBookName = res.groups[0].group_name
				listBookAccounts();
			}
		})
	}
	
	const listBookAccounts = () => {
		callCloudFunction({
			name: 'ume-notebook',
			data: {action: 'userRetrieve', params: {group: bookConfig.currentBookId}}
		}).then(res => {
			// console.log('booAccounts:', res);
			bookData.accounts = res.data.map(item => {
				// console.log(item);
				let username = decryptString(item.account)
				let userkey = decryptString(item.passkey)
				// console.log('username:', username);
				// console.log('userkey:', userkey);
				return {
					_id: item._id,
					username: username,
					// username: item.account,
					userkey: userkey,
					note: item.note,
					explain: false,
					keyHide: '*'.repeat(userkey.length)
				}
			})
			bookData.hasAccount = bookData.accounts.length > 0
			// console.log('bookData:', bookData.accounts);
		})
	}
	// 获取我的密码本子
	onMounted(() => {
		setCurrentPrivateKey(); // 设置当前设备密钥
		listBooks();
	})
</script>

<style lang="scss" scoped>
  .content {
		background-color: #fff;
		.form-row {
		  display: flex;
		  flex-direction: row;
		  align-items: center;
		  border-bottom: 1px solid #eee;
		  .label {
		    width: 130rpx;
		    display: flex;
		    align-items: center;
		    flex-direction: row;
		    color: #555;
		    font-weight: 700;
		  }
		  .value {
		    margin-left: 20rpx;
		    width: 100%;
		    height: 60rpx;
		    input {
		      height: 60rpx;
		      color: #007aff;
		    }
		  }
		}
		
  	.manage-book {
			margin: 20rpx;
			padding-bottom: 20rpx;
			.title {
				text-align: center;
				margin: 20rpx 0;
				font-weight: 700;
				font-size: 32rpx;
			}
			.actions {
				margin-top: 10rpx;
				display: flex;
				justify-content: center;
			}
		}
		.pwd-key {
			display: flex;
			padding: 5rpx 20rpx;
			align-items: center;
			background-color: rgba(255, 112, 67, 0.1);
			.show-key {
				display: flex;
				flex: 1;
				padding: 0 15rpx;
				background-color: rgba(255, 112, 67, 0.11);
				border-radius: 4rpx;
			}
			.set-icon {
				margin-left: 10rpx;
			}
		}
		.private-key {
			.tn-red_text: {
				text-decoration: underline;
			}
		}
		.blank-content {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 90vh;
			.create-btn {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top:60rpx
			}
		}
  	// padding: 10rpx;
    .blocks {
			
      .block-box {
        // width: 100%;
        background-color: rgba(41, 135, 155, 0.1);
        padding: 10rpx;
        border-radius: 10rpx;
        .block-name {
          font-size: 28rpx;
          color: #888;
        }
        .block-items {
          display: flex;
					justify-content: flex-start;
					flex-wrap: wrap;
          .item {
            width: 80px;
            height: 80px;
            // border: 1px solid #000;
						// background-color: rgba(41, 135, 155, 0.1);
            margin: 4px;
            text-align: center;
						&.active {
							border-radius: 10px;
							background-color: rgba(41, 135, 155, 0.1);
						}
            .icon {
              width: 100%rpx;
              height: 60px;
              image {
                width: 60px;
                height: 60px;
              }
            }
            .name {
              font-size: 28rpx;
              line-height: 28rpx;
            }
          }
        }
      }
      
    }
		.popup-box, .key-form  {
		  .form {
		    padding: 20rpx;
		    .form-title {
		      line-height: 100rpx;
		      font-size: 38rpx;
		      font-weight: 700;
		    }
		    .form-row {
		      display: flex;
		      flex-direction: row;
		      align-items: center;
		      border-bottom: 1px solid #eee;
		      .label {
		        width: 130rpx;
		        display: flex;
		        align-items: center;
		        flex-direction: row;
		        color: #555;
		        font-weight: 700;
		      }
		      .value {
		        margin-left: 20rpx;
		        width: 100%;
		        height: 60rpx;
		        input {
		          height: 60rpx;
		          color: #007aff;
		        }
		      }
		    }
		  }
		
		}
		.book-list {
			line-height: 46rpx;
			.list-op {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 10rpx;
				background-color: rgba(255, 112, 67, 0.1);
			}
			.list-content {
				padding: 10rpx;
				.name {
					display: flex;
					.nindex {
					}
					.ntext {
						font-weight: 700;
						font-size: 32rpx;
						flex: 1;
						display: flex;
						// flex-wrap: wrap;
						// white-space: normal;
						word-wrap: break-word;
					}
				}
				.secret {
					padding-left: 45rpx;
					word-wrap: break-word;
				}
				.note {
					padding-left: 45rpx;
				}
			}
		}
	
		.acc-info {
			.title {
				color: #007aff;
				font-weight: 700;
			}
			.info {
				word-wrap: break-word;
				padding-left: 10rpx;
			}
		}
	}
</style>